package com.atguigu.tingshu.search.executor;

import com.atguigu.tingshu.common.constant.RedisConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @description:锁续期
 * @author: coilk
 * @date: 2025/3/24 23:54
 * @param: null
 * @return: null
 **/

public class ExpireThreadExecutor {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private Long ttl;
    private TimeUnit timeUnit;
    private StringRedisTemplate redisTemplate;
    private Long taskId;
    static ScheduledExecutorService scheduledExecutorService;
    static ScheduledFuture<?> scheduledFuture = null;

    static {
        scheduledExecutorService = Executors.newScheduledThreadPool(2);
    }

    public ExpireThreadExecutor(StringRedisTemplate redisTemplate, Long taskId) {
        this.redisTemplate = redisTemplate;
        this.taskId = taskId;
    }

    /**
     * 续期方法
     */
    public void renewal(Long ttl, TimeUnit timeUnit) {
        scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                logger.info("续期线程开始续期:");
                // 续期
                redisTemplate.expire(RedisConstant.ALBUM_LOCK_SUFFIX + taskId, ttl, timeUnit);
            }
        }, ttl / 3, ttl / 3, TimeUnit.SECONDS);
    }

    /**
     * 中断续期任务方法
     */
    public Boolean cancelRenewal() {
        boolean cancel = scheduledFuture.cancel(true);  // 取消给线程池的任务
        logger.info("续期线程结束续期:");
        return cancel;
    }
}
